/*
 * B 站直播弹幕抽奖机
 * 
 * @author Zdream
 * @date 2021-01-31
 * @since 0.4.1
 */

function create (context) {
	return {
		template : context.template,
		data : function () {
			return {
        roomId : null,
        lotteryTo : 1,
        // 状态数据
        status : null,
        countdownEnable : false,
        countdown : 0,
        anyWords : true,
        words : '',
        strategy : 'customer',
			}
		},
		props : {
			sid : String,
		},
		methods : {
			onScreenUpdated : function () {
        let status = this.status = context.getStatus(this.sid);
        if (!status || !status.data) {
					return;
				}
				if (status.data) {
          this.roomId = status.data.roomId <= 0 ? this.roomId : status.data.roomId;
          this.words = status.data.words;
          this.anyWords = this.words === '';
          this.strategy = status.data.strategy;
				}
			},
			countRemain : function () {
				// 计算还有多少人.
				if (this.status.data.phase >= 2) {
					return this.status.data.customers.filter(c => c.hp > 0).length;
				} else {
          return this.status.data.customers.length;
        }
			},
			// 事件驱动
			editRoomIdSubmit : function () {
        if (this.roomId == null) {
          //
          return;
        }
				context.sendCommand(this.sid, 'room', {roomId : this.roomId});
      },
      editCountdownSubmit : function () {
        let countdown = (this.countdownEnable) ? this.countdown : null;
        context.sendCommand(this.sid, 'begin', { countdown });
      },
      btnBegin : function () {
        context.sendCommand(this.sid, 'begin', { countdown : null });
      },
      btnReady : function () {
        context.sendCommand(this.sid, 'ready', null);
      },
      btnWords : function () {
        console.log('words');
        context.sendCommand(this.sid, 'words', { words : (this.anyWords) ? '' : this.words });
      },
      btnLotteryHalf : function () {
        let remain = this.countRemain();
        if (remain <= 1) return;
        this.btnLottery(parseInt(remain / 2));
      },
      btnLotteryMinusOne : function () {
        let remain = this.countRemain();
        if (remain <= 1) return;
        this.btnLottery(remain - 1);
      },
      btnLotteryTo : function () {
        this.btnLottery(this.lotteryTo);
      },
      btnLottery : function (num) {
        context.sendCommand(this.sid, 'lottery', { remain : num, strategy : this.strategy });
      },
		},
		mounted : function () {
			this.onScreenUpdated(); // 更新 chunkWidth
			context.getBus().$on('screen-status-sync-all', this.onScreenUpdated);
			context.getBus().$on('screen-updated', this.onScreenUpdated);
			context.getBus().$on('screen-destroyed', this.onScreenUpdated);
		},
    destroyed : function () {
      context.getBus().$off('screen-status-sync-all', this.onScreenUpdated);
      context.getBus().$off('screen-updated', this.onScreenUpdated);
      context.getBus().$off('screen-destroyed', this.onScreenUpdated);
    }
	};
}

export default create;
